﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ZF.BLL;
using System.Web.UI.HtmlControls;
using GCELibrary.Current;
using ZF.Model;
using System.Transactions;
using ZF.BLL.Page;
//jun
namespace ZF.WS.UserControls
{
    public partial class HouseEdit : System.Web.UI.UserControl
    {
        public IHouseEditPage HouseEditPage { get { return (IHouseEditPage)this.Page; } }
        public void Page_Load(object sender, EventArgs e)
        {
        }
        public SiteInfo SiteInfo { get { return SiteInfo.Instance; } }
        public WarnFactory WarnFactory { get { return ((IWarnFactoryPage)this.Page).WarnFactory; } }
        protected override void OnLoad(EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Request.UrlReferrer != null)
                {
                    this.ViewState["fromUrl"] = string.Concat(Request.UrlReferrer);
                }
            }
            base.OnLoad(e);
        }
        public void InitControls()
        {
            this.cblPeriphery.DataSource = DictionaryConfig.HPeriphery;
            this.cblPeriphery.DataBind();
            this.cblBaseFacility.DataSource = DictionaryConfig.HBaseFacility;
            this.cblBaseFacility.DataBind();
            this.cblWithFacility.DataSource = DictionaryConfig.HWithFacility;
            this.cblWithFacility.DataBind();
            this.rblDecoration.DataSource = DictionaryConfig.HDecoration;
            this.rblDecoration.DataBind();
            this.ddlDirection.DataSource = DictionaryConfig.HDirection;
            this.ddlDirection.DataBind();

            this.ddlDirection1.DataSource = this.ddlDirection.DataSource;
            this.ddlDirection1.DataBind();

            this.ddlHouseType.DataSource = DictionaryConfig.HHouseType;
            this.ddlHouseType.DataBind();
            this.ddlProperty.DataSource = DictionaryConfig.HProperty;
            this.ddlProperty.DataBind();
            var dt = HouseEditPage.DealType.ToString();
            foreach (Control c in this.Controls)
            {
                if (c is HtmlControl)
                {
                    var hc = (HtmlControl)c;
                    if (!string.IsNullOrEmpty(hc.Attributes["key"]))
                    {
                        hc.Visible = hc.Attributes["key"].Split(',').Contains(dt);
                    }
                }
            }
            var member = SiteInfo.GetCurrentMember();
            if (member != null && member.UserType == UserType.Admin && HouseEditPage.DealType == 4)
            {
                this.cbJp.Visible = true;
            }
            else
            {
                this.cbJp.Visible = false;
            }
            if (HouseEditPage.DealType == 2)
            {
                this.cbHZ.Checked = true;
            }
            HouseEditPage.Type = (HouseEditPage.OperType == PageOperType.AddNew ? "发布" : "修改") + SiteInfo.GetHouseTitle(HouseEditPage.DealType);
        }
        public void Add()
        {
            InitControls();
            var member=SiteInfo.GetCurrentMember();
            if(member!=null)
            {
                this.tbContact.Text = member.FullName;
                this.tbPubEmail.Text = member.EMail;
                this.tbQQ.Text = member.QQ;
                this.tbPhone.Text = member.Phone;
            }
        }
        public void AddSubmit(object sender, EventArgs e)
        {
            using (var ts = new TransactionScope())
            {
                using (var dc = SiteInfo.CreateDBDataContext())
                {
                    var house = new Model.H_House()
                    {
                        AreaId1 = this.tbCity.Text.Convert<int>(),
                        AreaId2 = this.tbArea.Text.EmptyInt(),
                        Address = this.tbAddress.Text,
                        AddTime = DateTime.Now,
                        Age = this.tbAge.Text,
                        BaseFacility = this.cblBaseFacility.SelectedValues.ConstituteString(),
                        Periphery = this.cblPeriphery.SelectedValues.ConstituteString(),
                        Contact = this.tbContact.Text,
                        CutNum = this.tbCutNum.Text,
                        Form = this.rblForm.SelectedValue.Convert<int>(),
                        QQ = this.tbQQ.Text,
                        Decoration = this.rblDecoration.SelectedValue,
                        Title = this.tbTitle.Text,
                        Direction = this.ddlDirection.SelectedValue + "|" + this.ddlDirection1.SelectedValue,
                        HX_Chu = this.ddlHXChu.SelectedValue.Convert<int>(),
                        HX_Fan = this.ddlHXFan.SelectedValue.Convert<int>(),
                        HX_Tin = this.ddlHXTin.SelectedValue.Convert<int>(),
                        HX_Wei = this.ddlHXWei.SelectedValue.Convert<int>(),
                        HX_Yan = this.ddlHXYan.SelectedValue.Convert<int>(),
                        HouseType = this.ddlHouseType.SelectedValue,
                        WithFacility = this.cblWithFacility.SelectedValues.ConstituteString(),
                        TopNum = this.tbTopNum.Text,
                        Phone = this.tbPhone.Text,
                        Period = this.ddlPeriod.SelectedValue,
                        Description = this.tbDescription.Text,
                        Traffic = this.tbTraffic.Text,
                        UserArea = this.tbUserArea.Text,
                        ConstructArea = this.tbConstructArea.Text,
                        Engage = this.tbEngage.Text,
                        PubEmail = this.tbPubEmail.Text,
                        Status = 1,
                        MemberId = SiteInfo.GetCurrentMember() != null ? SiteInfo.GetCurrentMember().MemberId : 0,
                        IsMemberPub = SiteInfo.GetCurrentMember() != null,
                        IsVerify = SiteInfo.SystemConfig.HousePubVerify,
                        Photo = this.SWFUpLoad1.UpLoadFileInfos.ConstituteString(";"),
                        Payment = this.tbPayment.Text.EmptyString(),
                        IsBoutique=this.cbJp.Checked,
                    };
                    if (HouseEditPage.DealType == 3 || HouseEditPage.DealType == 4)//如果是售房
                    {

                        house.DealType = HouseEditPage.DealType;
                        house.Price = this.tbSFPrice.Text.Convert<int>();
                        var sell = new H_Sell()
                        {
                            UnitPrice = this.tbUnitPrice.Text.EmptyInt(),
                            Preferential = this.tbPreferential.Text,
                            Property = this.ddlProperty.SelectedValue,
                        };
                        house.H_Sell = sell;
                    }
                    else if (HouseEditPage.DealType == 1 || HouseEditPage.DealType == 2)//如果是租房 
                    {
                        house.DealType = this.cbHZ.Checked ? 2 : 1;
                        house.Price = this.tbZFPrice.Text.Convert<int>();
                        var rent = new H_Rent()
                        {
                            EnterTime = this.tbEnterTime.Text.EmptyString(),
                            HZ_ISex = this.rblHZ_ISex.SelectedValue.Convert<int>(),
                            HZ_RSex = this.rblHZ_RSex.SelectedValue.Convert<int>(),

                            HZDescription = this.tbHZDescription.Text.EmptyString(),
                            LeastNum = this.ddlLeastNum.SelectedValue.Convert<int>(),
                        };
                        house.H_Rent = rent;
                    }
                    else
                    {
                        throw new Exception();
                    }
                    SiteInfo.CheckFilterWords(house);
                    try
                    {
                        dc.H_House.InsertOnSubmit(house);
                        dc.SubmitChanges();
                        ts.Complete();
                    }
                    catch (Exception ex)
                    {
                        throw WarnFactory.CreateWarn(ex);
                    }
                    string msgKey = SiteInfo.GetHouseTitle(house.DealType);
                    //SiteInfo.InsertLog(string.Format("添加{0}--{1}成功", msgKey, pos.PosName),
                    //    string.Format("监控点id:{0},归属企业id:{1},操作帐号:{2}",
                    //    pos.PosId, CurrentUser.UserGroup.UserGroupId, CurrentUser.Account));
                    SiteInfo.InsertLog("发布" + msgKey, null);
                    WarnMessageLink link = new WarnMessageLink(string.Format("成功发布一个{0}，点击确定按钮返回上一页", msgKey));
                    link.AddWarnMessageLink(string.Format("查看该{0}", msgKey),
                        string.Format("/House/HouseInfo.aspx?hid={0}", house.HouseId));
                    link.AddWarnMessageLink(string.Format("继续发布{0}", msgKey),
                        Request.Url.ToString());

                    var fromUrl = this.ViewState["fromUrl"];
                    if (fromUrl != null)
                    {
                        WarnFactory.CreateWarn(link.ToString(), WarnIcon.Success, fromUrl.ToString()).Alert();
                    }
                    else
                    {
                        WarnFactory.CreateWarn(link.ToString(), WarnIcon.Success, WarnLink.GoBack).Alert();
                    }
                }
            }
        }
        public void Edit()
        {
            using (var dc = BLL.SiteInfo.CreateDBDataContext())
            {
                var member = SiteInfo.GetCurrentMember();
                if (member == null)
                    throw WarnFactory.CreateWarn(WarnCode.LoginTimeOut);
                var sel = dc.H_House.Where(p=> p.HouseId == HouseEditPage.HouseId );
                if (member.UserType != UserType.Admin)
                    sel = sel.Where(p => p.MemberId == member.MemberId);
                var house = sel.FirstOrDefault();
                if (house == null)
                    throw WarnFactory.CreateWarn(WarnCode.ReocrdNoFind);
                HouseEditPage.DealType = house.DealType;
                InitControls(); ;
                this.tbCity.Text = house.AreaId1.ToString();
                this.tbArea.Text = house.AreaId2.ToString();
                this.tbAddress.Text = house.Address;
                this.tbAge.Text = house.Age;
                this.cblBaseFacility.SelectedValues = house.BaseFacility.Split(',');
                this.cblPeriphery.SelectedValues = house.Periphery.Split(',');
                this.tbContact.Text = house.Contact;
                this.tbCutNum.Text = string.Concat(house.CutNum);
                this.rblForm.SelectedValue = house.Form.ToString();
                this.tbQQ.Text = house.QQ;
                this.rblDecoration.SelectedValue = house.Decoration;
                this.tbTitle.Text = house.Title;
                var directions = house.Direction.Split('|').ToList(); directions.Add("-"); directions.Add("-");
                this.ddlDirection.SelectedValue = directions[0];
                this.ddlDirection1.SelectedValue = directions[1];
                this.ddlHXChu.SelectedValue = house.HX_Chu.ToString();
                this.ddlHXFan.SelectedValue = house.HX_Fan.ToString();
                this.ddlHXTin.SelectedValue = house.HX_Tin.ToString();
                this.ddlHXWei.SelectedValue = house.HX_Wei.ToString();
                this.ddlHXYan.SelectedValue = house.HX_Yan.ToString();
                this.ddlHouseType.SelectedValue = house.HouseType.ToString();
                this.cblWithFacility.SelectedValues = house.WithFacility.EmptyString("").Split(',');
                this.tbTopNum.Text = string.Concat(house.TopNum);
                this.tbPhone.Text = house.Phone;
                this.ddlPeriod.SelectedValue = house.Period;
                this.tbDescription.Text = house.Description;
                this.tbTraffic.Text = house.Traffic;
                this.tbUserArea.Text = string.Concat(house.UserArea);
                this.tbConstructArea.Text = string.Concat(house.ConstructArea);
                this.tbEngage.Text = house.Engage;
                this.tbPubEmail.Text = house.PubEmail;
                this.tbPayment.Text = house.Payment;
                this.tbPhoto.Text = house.Photo;
                this.cbJp.Checked = house.IsBoutique;
                this.lvImgList.DataSource = house.Photo.EmptyString("").Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries)
                    .Select(p => new
                    {
                        File = p
                    });
                this.lvImgList.DataBind();
                if ((house.DealType ==3 || house.DealType ==4) && house.H_Sell != null)
                {
                    this.tbUnitPrice.Text = string.Concat(house.H_Sell.UnitPrice);
                    this.tbPreferential.Text = house.H_Sell.Preferential;
                    this.tbSFPrice.Text = house.Price.ToString();
                    this.ddlProperty.SelectedValue = house.H_Sell.Property;
                }
                else if ((house.DealType ==1 || house.DealType==2) && house.H_Rent != null)
                {
                    if (house.DealType == 2)
                        this.cbHZ.Checked = true;
                    var rent = house.H_Rent;
                    this.tbEnterTime.Text = rent.EnterTime;
                    this.rblHZ_ISex.SelectedValue = rent.HZ_ISex.ToString();
                    this.rblHZ_RSex.SelectedValue = rent.HZ_RSex.ToString();
                    this.tbHZDescription.Text = rent.HZDescription;
                    this.ddlLeastNum.SelectedValue = rent.LeastNum.ToString();
                    this.tbZFPrice.Text = house.Price.ToString();

                }
              


            }
        }
        public void EditSubmit(object sender, EventArgs e)
        {
            using (var ts = new System.Transactions.TransactionScope())
            {
                using (var dc = BLL.SiteInfo.CreateDBDataContext())
                {
                    var member = SiteInfo.GetCurrentMember();
                    if (member == null)
                        throw WarnFactory.CreateWarn(WarnCode.LoginTimeOut);
                    var sel = dc.H_House.Where(p => p.HouseId == HouseEditPage.HouseId);
                    if (member.UserType != UserType.Admin)
                        sel = sel.Where(p => p.MemberId == member.MemberId);
                    var house = sel.FirstOrDefault();
                    if (house == null)
                        throw WarnFactory.CreateWarn(WarnCode.ReocrdNoFind);
                    house.AreaId1 = this.tbCity.Text.Convert<int>();
                    house.AreaId2 = this.tbArea.Text.EmptyInt();
                    house.Address = this.tbAddress.Text;
                    house.Age = this.tbAge.Text;
                    house.BaseFacility = this.cblBaseFacility.SelectedValues.ConstituteString();
                    house.Periphery = this.cblPeriphery.SelectedValues.ConstituteString();
                    house.Contact = this.tbContact.Text;
                    house.CutNum = this.tbCutNum.Text;
                    house.Form = this.rblForm.SelectedValue.Convert<int>();
                    house.QQ = this.tbQQ.Text;
                    house.Decoration = this.rblDecoration.SelectedValue;
                    house.Title = this.tbTitle.Text;
                    house.Direction =  this.ddlDirection.SelectedValue + "|" + this.ddlDirection1.SelectedValue;
                    house.HX_Chu = this.ddlHXChu.SelectedValue.Convert<int>();
                    house.HX_Fan = this.ddlHXFan.SelectedValue.Convert<int>();
                    house.HX_Tin = this.ddlHXTin.SelectedValue.Convert<int>();
                    house.HX_Wei = this.ddlHXWei.SelectedValue.Convert<int>();
                    house.HX_Yan = this.ddlHXYan.SelectedValue.Convert<int>();
                    house.HouseType = this.ddlHouseType.SelectedValue;
                    house.WithFacility = this.cblWithFacility.SelectedValues.ConstituteString();
                    house.TopNum = this.tbTopNum.Text;
                    house.Phone = this.tbPhone.Text;
                    house.Period = this.ddlPeriod.SelectedValue;
                    house.Description = this.tbDescription.Text;
                    house.Traffic = this.tbTraffic.Text;
                    house.UserArea = this.tbUserArea.Text; 
                    house.ConstructArea = this.tbConstructArea.Text;
                    house.Engage = this.tbEngage.Text;
                    house.PubEmail = this.tbPubEmail.Text;
                    house.IsBoutique = this.cbJp.Checked;
                    var photoList = this.tbPhoto.Text.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries).ToList();
                    photoList.AddRange(this.SWFUpLoad1.UpLoadFileInfos);
                    house.Photo = photoList.ConstituteString(";"); ;
                    house.Payment = this.tbPayment.Text;
                    if (house.DealType == 3 || house.DealType == 4)//如果是售房
                    {
                        house.Price = this.tbSFPrice.Text.Convert<int>();
                        var sell = house.H_Sell;
                        sell.UnitPrice = this.tbUnitPrice.Text.EmptyInt();
                        sell.Preferential = this.tbPreferential.Text;
                        sell.Property = this.ddlProperty.SelectedValue;
                    }
                    else if (house.DealType == 1 || house.DealType == 2)//如果是租房 
                    {
                        house.DealType = this.cbHZ.Checked ? 2 : 1;
                        house.Price = this.tbZFPrice.Text.Convert<int>();
                        var rent = house.H_Rent;
                        rent.EnterTime = this.tbEnterTime.Text.EmptyString();
                        rent.HZ_ISex = this.rblHZ_ISex.SelectedValue.Convert<int>();
                        rent.HZ_RSex = this.rblHZ_RSex.SelectedValue.Convert<int>();
                        rent.HZDescription = this.tbHZDescription.Text.EmptyString();
                        rent.LeastNum = this.ddlLeastNum.SelectedValue.Convert<int>();
                    }
                    else
                    {
                        throw new Exception();
                    }
                    SiteInfo.CheckFilterWords(house);
                    try
                    {
                        dc.SubmitChanges();
                        ts.Complete();
                    }
                    catch (Exception ex)
                    {
                        throw WarnFactory.CreateWarn(ex);
                    }
                    string msgKey = SiteInfo.GetHouseTitle(house.DealType);
                    SiteInfo.InsertLog("修改" + msgKey, null);
                    WarnMessageLink link = new WarnMessageLink(string.Format("成功修改一个{0}，点击确定按钮返回{0}列表", msgKey));
                    link.AddWarnMessageLink(string.Format("查看该{0}", msgKey),
                        string.Format("/House/HouseInfo.aspx?hid={0}", house.HouseId));
                    link.AddWarnMessageLink(string.Format("重新修改{0}", msgKey),
                        Request.Url.ToString());
                    var fromUrl = this.ViewState["fromUrl"];

                    if (fromUrl != null)
                    {
                        WarnFactory.CreateWarn(link.ToString(), WarnIcon.Success, fromUrl.ToString()).Alert();
                    }
                    else
                    {
                        WarnFactory.CreateWarn(link.ToString(), WarnIcon.Success, WarnLink.GoBack).Alert();
                    }
                }
            }

        }
    }
}